//
//  BroccolisCircleMenu.m
//  CircleRotateMenu
//
//  Created by JLei on 2018/6/28.
//  Copyright © 2018年 Broccolis. All rights reserved.
//

#import "BroccolisCircleMenu.h"


#define Bro_CircleWidth 310
#define Bro_CircleHeight 310

@interface BroccolisCircleMenu() <UIGestureRecognizerDelegate>
{
    CGPoint beginPoint;
    float mStartAngle;
    CGPoint movePoint;
}
//按钮数组
@property (nonatomic, strong) NSMutableArray *btnArray;
//弧度
@property (nonatomic, assign) CGFloat rotationAngleInRadians;
//中心按钮
@property (nonatomic, strong) UIButton *centerButton;
//是否展开
@property (nonatomic, assign) BOOL isShow;

@end
@implementation BroccolisCircleMenu

static BroccolisCircleMenu *shareInstance;

+ (instancetype)sharedCircleView{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance = [[BroccolisCircleMenu alloc] init];
    });
    return shareInstance;
}

- (instancetype)init{
    if (self = [super init]) {
        self.userInteractionEnabled = YES;
        self.frame = CGRectMake(0, 0, Bro_CircleWidth, Bro_CircleHeight);
        self.backgroundColor = [UIColor whiteColor];
        self.layer.cornerRadius = Bro_CircleHeight/2;
        [self initData];
        self.rotationAngleInRadians = 0.0000001;
        self.hidden = YES;
        _isShow = NO;
        
    }
    return self;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}

- (void)initData{
    
    self.centerButton = [[UIButton alloc] initWithFrame:CGRectMake(self.center.x, self.center.y, 80, 80)];
    [self.centerButton setBackgroundImage:[UIImage imageNamed:@"greencenter"] forState:0];
    self.centerButton.layer.masksToBounds = YES;
    self.centerButton.layer.cornerRadius = 40;
    [self.centerButton addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchDown];
    [self addSubview:self.centerButton];
    self.centerButton.center = CGPointMake(self.center.x, self.center.y);
    
    _btnArray = [NSMutableArray array];
}

- (void)configBtnWithTitles:(NSArray *)titleArr andImages:(NSArray *)imageArr {
    
    for (int i = 0; i < titleArr.count; i ++) {
        UIView *btn = [[UIButton alloc] initWithFrame:CGRectMake(Bro_CircleWidth/2-25, Bro_CircleHeight/2-25, 82, 80)];
        btn.alpha = 0;
        btn.tag = 1000 + i;
        btn.layer.cornerRadius = 20;
        btn.userInteractionEnabled = YES;
        [self addSubview:btn];
        
        UIImageView *topImage = [UIImageView new];
        topImage.userInteractionEnabled = YES;
        topImage.tag = 1000 + i;
        [topImage setImage:[UIImage imageNamed:imageArr[i]]];
        [btn addSubview:topImage];
        [topImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(btn);
            make.top.equalTo(btn.mas_top).offset(10);
        }];

        UILabel *bottomLabel = [UILabel new];
        bottomLabel.tag = 1000 + i;
        bottomLabel.userInteractionEnabled = YES;
        bottomLabel.text = titleArr[i];
        bottomLabel.font = [UIFont systemFontOfSize:14];
        bottomLabel.textAlignment = NSTextAlignmentCenter;
        [btn addSubview:bottomLabel];
        [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(btn);
            make.top.equalTo(topImage.mas_bottom).offset(4);
        }];

        UIView *clearView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 82, 80)];
        clearView.backgroundColor = [UIColor clearColor];
        clearView.tag = 1000 + i;
        clearView.layer.cornerRadius = 20;
        [btn addSubview:clearView];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClickBtn:)];
        [clearView addGestureRecognizer:tap];
        
        UIPanGestureRecognizer *panges = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(changeRomate:)];
        panges.delegate = self;
        [clearView addGestureRecognizer:panges];
        
        
        [_btnArray addObject:btn];
    }
    
}

- (void)hideAllBtns {
    __weak __typeof(self)weakself = self;
    [UIView animateWithDuration:0.1 animations:^{
        
        for (int i = 0; i < weakself.btnArray.count; i ++) {
            UIView *btn = weakself.btnArray[i];
            btn.center = CGPointMake(Bro_CircleWidth/2, Bro_CircleHeight/2);
            btn.alpha = 0;
        }
        
        self.hidden = YES;
    }];
    [self showOtherBtn:NO];
    _isShow = NO;
}

- (void)show{
    __weak __typeof(self)weakself = self;

    //展示全部按钮
    if (!_isShow) {
        
        self.transform = CGAffineTransformMakeRotation(-M_PI_2/22);
        self.centerButton.transform = CGAffineTransformMakeRotation(M_PI_2/22);
        for (UIView *btn in _btnArray) {
            btn.transform = CGAffineTransformMakeRotation(M_PI_2/22);
        }
        
        self.rotationAngleInRadians = -M_PI_2/22;
        
        [UIView animateWithDuration:0.1 animations:^{
            //夹角 = 360度 / 按钮个数
            CGFloat corner = - M_PI * 2.0 / self.btnArray.count;
            //半径
            CGFloat r = 110;
            CGFloat x = Bro_CircleWidth/2.0;
            CGFloat y = Bro_CircleHeight/2.0;
            
            for (int i = 0; i < weakself.btnArray.count; i ++) {
                UIView *btn = weakself.btnArray[i];
                CGFloat ti = (i+3-0.1) * 1.0;
                btn.center = CGPointMake(x + r * cos(corner * ti), y + r *sin(corner * ti));
                btn.alpha = 1;
            }
            
            
            
            self.hidden = NO;
        }];
        [self showOtherBtn:YES];
    }else{
        
        
        [UIView animateWithDuration:0.1 animations:^{
            
            for (int i = 0; i < weakself.btnArray.count; i ++) {
                UIView *btn = weakself.btnArray[i];
                btn.center = CGPointMake(Bro_CircleWidth/2, Bro_CircleHeight/2);
                btn.alpha = 0;
            }
            
            self.hidden = YES;
            
        }];
        [self showOtherBtn:NO];
    }
    
    _isShow = !_isShow;
    
}

- (void)showOtherBtn:(BOOL)ifShow {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(showStaticBtn:)]) {
        [self.delegate showStaticBtn:ifShow];
    }
    
}

- (void)tapClickBtn:(UIGestureRecognizer *)ges {
    _isShow = YES;
    [self show];
    
    NSInteger index = [ges view].tag >= 1000 ? [ges view].tag - 1000 : [ges view].tag;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickBtnWithIndex:)]) {
        [self.delegate clickBtnWithIndex:index];
    }
}

#pragma mark 点击菜单按钮
- (void)clickButton:(UIButton *)sender{
    
    _isShow = YES;
    [self show];
    
    NSInteger index = sender.tag >= 1000 ? sender.tag - 1000 : sender.tag;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(clickBtnWithIndex:)]) {
        [self.delegate clickBtnWithIndex:index];
    }
    
}

//获取当前点弧度
- (float)getAngle:(CGPoint)point {
    double x = point.x ;
    double y = point.y ;
    return (float) (asin(y / hypot(x, y)));
}

//旋转手势
- (void)changeRomate:(UIGestureRecognizer *)rotation{
    
    if(rotation.state==UIGestureRecognizerStateBegan){
        beginPoint=[rotation locationInView:self.superview];
    }else if (rotation.state == UIGestureRecognizerStateChanged) {
        movePoint= [rotation locationInView:self.superview];
        
        mStartAngle = atan2f(movePoint.y - self.center.y, movePoint.x - self.center.x) - atan2f(beginPoint.y - self.center.y, beginPoint.x - self.center.x);
        self.transform = CGAffineTransformMakeRotation((self.rotationAngleInRadians+mStartAngle));
        self.centerButton.transform = CGAffineTransformMakeRotation(-(self.rotationAngleInRadians+mStartAngle));
        for (UIView *btn in _btnArray) {
            btn.transform = CGAffineTransformMakeRotation(-(self.rotationAngleInRadians+mStartAngle));
        }
        
        beginPoint=movePoint;
    }
    
    
    self.rotationAngleInRadians += mStartAngle;
    
}

@end
